﻿using System;
using System.Collections.Generic;
using Yzq.Utilities;
using DO;
using UnityEngine;
using System.Linq;
using Yzq.BLL;
using Yzq.AudioConvert;

namespace Yzq.Dialogue
{
    public class Data_Context : A0101_MonoSingleton<Data_Context>
    {
        public event Action<AudioClip> OnConvertedToAudioClip;
        public event Action<string, string> OnConversationUpdated;

        public List<E01_MsglineDO> ConversationHistory { get; private set; } = new List<E01_MsglineDO>();
        public Action<string, string> UpdateConversationHistory => (role, content) =>
        {
            ConversationHistory.Add(new E01_MsglineDO { role = role, content = content });
            OnConversationUpdated?.Invoke(role, content); // 触发事件通知UI更新
        };


        /// <summary>

        /// <summary>
        /// 2.1 将响应JSON字符串解析为ResponseDTO对象并依次处理。
        /// </summary>
        /// <param name="jsonResponse"></param>
        public void ProcessResponseData(string jsonResponse)
        {
            try
            {
                EP02_VideoResponseDTO responseDTO = JsonUtility.FromJson<EP02_VideoResponseDTO>(jsonResponse);
                ProcessResponseBytesAudio(responseDTO.audio_output);
                UpdateConversationHistory("user", responseDTO.text_input);
                UpdateConversationHistory("assistant", responseDTO.text_output);

            }
            catch (Exception ex)
            {
                Debug.LogError($"解析响应数据过程中发生错误: {ex.Message}");
            }
        }
        /// <summary>
        /// 2.2
        /// </summary>
        /// <param name="audioBase64"></param>
        public void DecodeResponseBase64Audio(string audioBase64)
        {
            //OnConvertedToAudioClip?.Invoke(AudioConverter.ConvertBase64ToClip(audioBase64));
        }
        public void ProcessResponseBytesAudio(byte[] audio_bytes)
        {
            OnConvertedToAudioClip?.Invoke(AudioClipConverter.ConvertBytesToClip(audio_bytes));
        }
    }
}